from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
import traceback

from Basic.api_mysql import pymysqlHandle
from Basic.read_ini import ReadIni
from Basic.base_log import log
from Basic.PATH import *
from Basic.read_re import re_sub
'''
可在浏览器中按 F12 --> console --> 输入命令 document.getElementsByClassName("ele")进行查找元素调试
'''


class GetElement(object):
    def __init__(self, driver):
        self.driver = driver #seleium
        self.readini = ReadIni()
        self.time1 = int(self.readini.get_value('time','time1'))
        self.time2 = int(self.readini.get_value('time','time2'))


    #需传入参数dict(从excel获取到的每行用例所有的参数的对应值)
    def get_ele(self, caseDict, assert_flag=False):
        #excel表格参数初始化
        case_module = caseDict['用例模块']
        case_id = caseDict['编号']
        precondition = caseDict['前提条件']
        operate_step = caseDict['操作步骤']
        element_operate = caseDict['操作元素']
        element_method = caseDict['元素定位方式']
        elemernt_action = caseDict['元素动作']
        element_sendkey = caseDict['输入数据']
        bool_execute = caseDict['是否执行']

        # 断言如何一对多?
        assert_ele = caseDict['断言元素']
        assert_ele_method = caseDict['断言元素方法']
        assert_ele_action = caseDict['断言元素动作']
        assert_method = caseDict['断言方法']
        except_result = caseDict['预期结果']
        assert_result = caseDict['断言结果']
        # log.info('getele获取到的全局变量：%s' % var_dict)

        # 设置默认返回值
        ele = None
        try:
            #执行断言获取元素
            if assert_flag == True:
                by = self.get_by(assert_ele_method)
                # log.info('--   --> 执行断言')
                # log.info('--   --> 执行断言，预期结果：%s，实际结果：%s ' % (except_result, test_results))
                # 打印操作
                if assert_ele_action in 'ele text sql':
                    ele = WebDriverWait(self.driver, self.time1, self.time2).until(
                        EC.visibility_of_element_located((by, assert_ele)))
                else:
                    # error_log = ('--   --> 该操作类型:%s 未匹配，请检查后重试' % assert_ele_action)
                    # self.readini.set_value('error', 'error_log', error_log)
                    # log.info(error_log)
                    return None
                return ele

        except:
            error_log = "*××××××××××××××××××get_element 出错××××××××××××××××××\n %s" % traceback.format_exc()  # 打印异常信息
            # self.readini.set_value('error', 'error_log', error_log)
            log.info(error_log)
            return False

        try:
            # 获取元素
            by = self.get_by(element_method)
            '''全部18：click text scroll handle iframe ifele ifclick screenshot getcode  sendky url assert checkbox1 checkbox2 clickxy hover waitele requests get get_var set_var upload'''
            # 打印操作
            if elemernt_action in 'click text checkbox1 checkbox2 scroll handle ifele iframe ifclick screenshot getcode hover requests get  get_var set_var get_table':
                log.info('-- %s --> %s: ' % (case_id, operate_step))
            elif elemernt_action in 'sendkey':
                log.info('-- %s --> %s:%s ' % (case_id, operate_step, element_sendkey))
            elif elemernt_action in 'url clickxy_ele  upload':
                log.info('-- %s --> %s:%s ' % (case_id, operate_step, element_operate))
            elif elemernt_action == 'assert':
                log.info(
                    '-- %s --> %s: %s %s %s ' % (case_id, operate_step, assert_method, except_result, assert_result))
            else:
                error_log = ('--   --> 该操作类型:%s 未匹配，请检查后重试1' % elemernt_action)
                self.readini.set_value('error', 'error_log', error_log)
                log.info(error_log)
                return None

            # 获取元素
            if elemernt_action in 'click sendkey text checkbox1 checkbox2 scroll iframe getcode hover upload':
                ele = WebDriverWait(self.driver, self.time1, self.time2).until(
                    EC.visibility_of_element_located((by, element_operate)))
            elif elemernt_action in 'ifele ifclick':
                ele = self.if_ele(by, element_operate)
            elif elemernt_action in 'clickxy_ele':
                if element_method != 'get':
                    ele = WebDriverWait(self.driver, self.time1, self.time2).until(
                        EC.visibility_of_element_located((by, element_operate)))
                else:
                    ele = 1
            elif elemernt_action == 'handle':
                ele = self.driver.current_window_handle  # 定位当前页面句柄
            elif elemernt_action == 'set_var':
                if element_method != 'get':
                    ele = WebDriverWait(self.driver, self.time1, self.time2).until(
                        EC.visibility_of_element_located((by, element_operate)))
                else:
                    ele = 1
            elif elemernt_action in 'url screenshot assert requests get get_var set_var sup_var':
                ele = 1
            elif elemernt_action in 'waitele':
                ele = self.wait_ele(by, element_operate,int(element_sendkey))
            elif elemernt_action in 'get_table':
                ele = self.get_table(by, element_operate)
            elif elemernt_action in 'get_sql':
                db = pymysqlHandle('root', 'root', '3306', 'database')
                ele = db.selectDb(caseDict['操作元素'])
            else:
                error_log = ('--   --> 该操作类型:%s 未匹配，请检查后重试2' % elemernt_action)
                self.readini.set_value('error', 'error_log', error_log)
                log.info(error_log)
                return None
            return ele
        except :
            error_log = "*××××××××××××××××××get_element 出错××××××××××××××××××\n %s" % traceback.format_exc()  # 打印异常信息
            # self.readini.set_value('error', 'error_log', error_log)
            log.info(error_log)
            return False

    #获取by
    def get_by(self,element_type):
        by = None
        if element_type == 'XPATH':
            by = By.XPATH
        elif element_type == 'CSS_SELECTOR':
            by = By.CSS_SELECTOR
        elif element_type == 'ID':
            by = By.ID
        elif element_type == 'CLASS_NAME':
            by = By.CLASS_NAME
        elif element_type == 'NAME':
            by = By.NAME
        elif element_type == 'TAG_NAME':
            by = By.TAG_NAME
        elif element_type == 'LINK_TEXT':
            by = By.LINK_TEXT
        # elif element_type == 'handle':#切换窗口
        # elif element_type == 'screenshot'#截图:
        # elif element_type == 'get'#接口测试:
        return by

    def if_ele(self,by,operate_element):
        try:
            ele = WebDriverWait(self.driver, self.time1, self.time2).until(
                EC.visibility_of_element_located((by, operate_element)))
            return ele
        except:
            return 'ERROR'

    def wait_ele(self,by,operate_element, time2):
        try:
            ele = WebDriverWait(self.driver, self.time1, time2).until(
                EC.visibility_of_element_located((by, operate_element)))
            return ele
        except:
            return 'ERROR'
        return


    def get_driver(self):
        driver = webdriver.Chrome()
        driver.maximize_window()
        return driver

    def get_table(self,by,element_operate):
        # 表头classname=el-table__header-wrapper//tr/th
        # 表格classname=el-table__body //tr/td
        # 定位table元素
        table = WebDriverWait(self.driver, self.time1, self.time2).until(
            EC.visibility_of_element_located((by, element_operate)))
        # 获取表头字段,值为空保存成字典
        table_header = table.find_element(By.CLASS_NAME, 'el-table__header-wrapper')
        thlist = table_header.find_elements(By.TAG_NAME, 'th')
        # log.info('thlist:%s' % thlist)
        # 获取数据行数
        table_body = table.find_element(By.CLASS_NAME, 'el-table__body-wrapper')
        trlist = table_body.find_elements(By.TAG_NAME, 'tr')
        tblist = []
        tbdict = {}
        # 循环获取每行的值，保存成字典
        for row in trlist:
            for col in range(len(thlist)):
                # log.info(thlist[col].text)
                tdlist = row.find_elements(By.TAG_NAME, 'td')
                tbdict[thlist[col].text] = tdlist[col].text
                if '状态' in tbdict.keys():
                    if tbdict['状态'] == '':
                        switch = tdlist[col].find_element(By.CLASS_NAME, 'el-switch__core')
                        # 获取按钮颜色
                        color = switch.value_of_css_property("background-color")
                        if color == 'rgba(220, 223, 230, 1)':
                            tbdict['状态'] = 0
                        else:
                            tbdict['状态'] = 1
                        # log.info('background-color:%s' % tbdict['状态'])
                # log.info('table_dict:%s' % table_dict)
            # log.info('table_dict:%s' % tbdict)
            if '' in tbdict.keys():
                del (tbdict[''])
            tblist.append(tbdict)
            tbdict = {}
        # log.info('获取到的表格数据list_table:%s' % tblist)
        # 通过输入数据判断是新增的哪一行，还是删除了
        list_table = tblist
        return list_table

if __name__ == "__main__":
    pass
